Tutorial 9: Regression Continued¶
Lecture and Tutorial Learning Goals:¶
By the end of the week, you will be able to:
- Recognize situations where a simple regression analysis would be appropriate for making predictions.
- Explain the $k$-nearest neighbour ($k$-nn) regression algorithm and describe how it differs from k-nn classification.
- Interpret the output of a $k$-nn regression.
- In a dataset with two variables, perform $k$-nearest neighbour regression in R using
tidymodelsto predict the values for a test dataset. - Using R, execute cross-validation in R to choose the number of neighbours.
- Using R, evaluate $k$-nn regression prediction accuracy using a test data set and an appropriate metric (e.g., root means square prediction error).
- In a dataset with > 2 variables, perform $k$-nn regression in R using
tidymodelsto predict the values for a test dataset. - In the context of $k$-nn regression, compare and contrast goodness of fit and prediction properties (namely RMSE vs RMSPE).
- Describe advantages and disadvantages of the $k$-nearest neighbour regression approach.
- Perform ordinary least squares regression in R using
tidymodelsto predict the values for a test dataset. - Compare and contrast predictions obtained from $k$-nearest neighbour regression to those obtained using simple ordinary least squares regression from the same dataset.
This tutorial covers parts of the Regression II chapter of the online textbook. You should read this chapter before attempting the worksheet.
### Run this cell before continuing.
library(tidyverse)
library(repr)
library(tidymodels)
library(GGally)
library(ISLR)
options(repr.matrix.max.rows = 6)
source("tests.R")
source("cleanup.R")
Predicting credit card balance¶
Source: https://media.giphy.com/media/LCdPNT81vlv3y/giphy-downsized-large.gif
Here in this worksheet we will work with a simulated data set that contains information that we can use to create a model to predict customer credit card balance. A bank might use such information to predict which customers might be the most profitable to lend to (customers who carry a balance, but do not default, for example).
Specifically, we wish to build a model to predict credit card balance (Balance column) based on income (Income column) and credit rating (Rating column).
We access this data set by reading it from an R data package that we loaded at the beginning of the worksheet, ISLR. Loading that package gives access to a variety of data sets, including the Credit data set that we will be working with. We will rename this data set credit_original to avoid confusion later in the worksheet.
credit_original <- Credit
credit_original
Question 1.1
{points: 1}
Select only the columns of data we are interested in using for our prediction (both the predictors and the response variable) and use the as_tibble function to convert it to a tibble (it is currently a base R data frame). Name the modified data frame credit (using a lowercase c).
Note: We could alternatively just leave these variables in and use our recipe formula below to specify our predictors and response. But for this worksheet, let's select the relevant columns first.
# your code here
#fail() # No Answer - remove if you provide an answer
credit <- credit_original|>
as_tibble()|>
select("Balance", "Income", "Rating")
Question 1.2
{points: 1}
Before we perform exploratory data analysis, we should create our training and testing data sets. First, split the credit data set. Use 60% of the data and set the variables we want to predict as the strata argument. Assign your answer to an object called credit_split.
Assign your training data set to an object called credit_training and your testing data set to an object called credit_testing.
set.seed(2000)
# your code here
#fail() # No Answer - remove if you provide an answer
credit_split <- initial_split(credit, prop = 0.60, strata = Balance)
credit_testing <- testing(credit_split)
credit_training <- training(credit_split)
Question 1.3
{points: 1}
Using only the observations in the training data set, use the ggpairs library create a pairplot (also called "scatter plot matrix") of all the columns we are interested in including in our model. Since we have not covered how to create these in the textbook, we have provided you with most of the code below and you just need to provide suitable options for the size of the plot.
The pairplot contains a scatter plot of each pair of columns that you are plotting in the lower left corner, the diagonal contains smoothed histograms of each individual column, and the upper right corner contains the correlation coefficient (a quantitative measure of the relation between two variables)
Name the plot object credit_pairplot.
options(repr.plot.height = 12, repr.plot.width = 12)
credit_pairplot <- credit_training |>
ggpairs(
lower = list(continuous = wrap('points', alpha = 0.4)),
diag = list(continuous = "barDiag")
) +
theme(text = element_text(size = 20))
# your code here
#fail() # No Answer - remove if you provide an answer
credit_pairplot
Question 1.4 Multiple Choice:
{points: 1}
Looking at the ggpairs plot above, which of the following statements is incorrect?
A. There is a strong positive relationship between the response variable (Balance) and the Rating predictor
B. There is a strong positive relationship between the two predictors (Income and Rating)
C. There is a strong positive relationship between the response variable (Balance) and the Income predictor
D. None of the above statements are incorrect
Assign your answer to an object called answer1.4. Make sure your answer is an uppercase letter and is surrounded by quotation marks (e.g. "F").
# your code here
#fail() # No Answer - remove if you provide an answer
answer1.4 <- "C"
Question 1.5
{points: 1}
Now that we have our training data, we will fit a linear regression model.
- Create and assign your linear regression model specification to an object called
lm_spec. - Create a recipe for the model. Assign your answer to an object called
credit_recipe.
set.seed(2020) #DO NOT REMOVE
# your code here
#fail() # No Answer - remove if you provide an answer
lm_spec <- linear_reg()|>
set_engine("lm")|>
set_mode("regression")
credit_recipe <- recipe(Balance ~ Income + Rating, data = credit_training)
print(lm_spec)
print(credit_recipe)
Question 1.6
{points: 1}
Now that we have our model specification and recipe, let's put them together in a workflow, and fit our simple linear regression model. Assign the fit to an object called credit_fit.
set.seed(2020) # DO NOT REMOVE
# your code here
#fail() # No Answer - remove if you provide an answer
credit_fit <- workflow() |>
add_recipe(credit_recipe)|>
add_model(lm_spec)|>
fit(data = credit_training)
credit_fit
Question 1.7 Multiple Choice:
{points: 1}
Looking at the slopes/coefficients above from each of the predictors, which of the following mathematical equations is correct for your prediction model?
A. $credit\: card \: balance = -528.014 -7.583*income + 3.937*credit\: card\: rating$
B. $credit\: card \: balance = -528.014 + 3.937*income -7.583*credit\: card\: rating$
C. $credit\: card \: balance = 528.014 -7.583*income - 3.937*credit\: card\: rating$
D. $credit\: card \: balance = 528.014 - 3.937*income + 7.583*credit\: card\: rating$
Assign your answer to an object called answer1.7. Make sure your answer is an uppercase letter and is surrounded by quotation marks (e.g. "F").
# your code here
#fail() # No Answer - remove if you provide an answer
answer1.7 <- "A"
Question 1.8
{points: 1}
Calculate the $RMSE$ to assess goodness of fit on credit_fit (remember this is how well it predicts on the training data used to fit the model). Return a single numerical value named lm_rmse.
set.seed(2020) # DO NOT REMOVE
lm_rmse <- credit_fit |>
predict(credit_training) |>
bind_cols(credit_training) |>
metrics(truth = Balance, estimate = .pred) |>
filter(.metric == "rmse") |>
select(".estimate") |>
pull()
# your code here
#fail() # No Answer - remove if you provide an answer
lm_rmse
Question 1.9
{points: 1}
Calculate $RMSPE$ using the test data. Return a single numerical value named lm_rmspe.
set.seed(2020) # DO NOT REMOVE
# your code here
#fail() # No Answer - remove if you provide an answer
lm_rmspe <- credit_fit |>
predict(credit_testing) |>
bind_cols(credit_testing) |>
metrics(truth = Balance, estimate = .pred) |>
filter(.metric == "rmse") |>
select(".estimate") |>
pull()
lm_rmspe
Question 1.9.1
{points: 3}
Redo this analysis using $k$-nn regression instead of linear regression. Use set.seed(2000) at the beginning of this code cell to make it reproducible. Use the same predictors and train - test data splits as you used for linear regression, and use 5-fold cross validation to choose $k$ from the range 1-10. Remember to scale and shift your predictors on your training data, and to apply that same standardization to your test data!
Assign a single numeric value for $RMSPE$ for your k-nn model as your answer, and name it knn_rmspe.
set.seed(2000) # DO NOT REMOVE
knn_tune <- nearest_neighbor (weight_func = "rectangular", neighbors = tune())|>
set_engine ("kknn")|>
set_mode ("regression")
credit_recipe_2 <- recipe(Balance ~ Income + Rating, data = credit_training)|>
step_scale(all_predictors())|>
step_center(all_predictors())
credit_vfold <- vfold_cv(credit_training, v = 5, strata = Balance)
credit_workflow <- workflow()|>
add_recipe(credit_recipe)|>
add_model(knn_tune)
gridvals <- tibble(neighbors = seq(from = 1, to = 10, by = 1))
knn_rmspe <- credit_workflow |>
tune_grid(resamples = credit_vfold, grid = gridvals)|>
collect_metrics()|>
filter(.metric == "rmse")|>
slice_min(mean, n = 1)
# This tells us that we should use 4 neighbors for our knn
knn_neighbor <- nearest_neighbor (weight_func = "rectangular", neighbors = 4)|>
set_engine("kknn")|>
set_mode("regression")
knn_workflow <- workflow()|>
add_recipe (credit_recipe_2)|>
add_model (knn_neighbor)|>
fit(data = credit_training)
knn_rmspe <- knn_workflow |>
predict(credit_testing) |>
bind_cols(credit_testing) |>
metrics(truth = Balance, estimate = .pred) |>
filter(.metric == "rmse") |>
select(".estimate") |>
pull()
#credit_result
# your code here
#fail() # No Answer - remove if you provide an answer
knn_rmspe
Question 1.9.2
{points: 3}
Discuss which model, linear regression versus $k$-nn regression, gives better predictions and why you think that might be happening.
Linear regression is a better model for making predictions than k-nn regression. I think this is happening because of the type of data we have. When we first looked at our data in Question 1.3, we could easily see that our variables (Income and Rating), both have a "linear" relationship, in the sense that the data provided shows that the growth is a straight line. When we have data of this type, linear regression typically performs better. This is because linear regression uses a line that best fits, to make approximations. Where as for Knn, it might not fair as well, since it is more flexible in terms of "curves" and shapes.
In short, this type of data is more suitable for linear regression, hence it performs better than knn regression
2. Ames Housing Prices¶

Source: https://media.giphy.com/media/xUPGGuzpmG3jfeYWIg/giphy.gif
If we take a look at the Business Insider report What do millenials want in a home?, we can see that millenials like newer houses that have their own defined spaces. Today we are going to be looking at housing data to understand how the sale price of a house is determined. Finding highly detailed housing data with the final sale prices is very hard, however researchers from Truman State Univeristy have studied and made available a dataset containing multiple variables for the city of Ames, Iowa. The data set describes the sale of individual residential property in Ames, Iowa from 2006 to 2010. You can read more about the data set here. Today we will be looking at 5 different variables to predict the sale price of a house. These variables are:
- Lot Area:
lot_area - Year Built:
year_built - Basement Square Footage:
bsmt_sf - First Floor Square Footage:
first_sf - Second Floor Square Footage:
second_sf
First, load the data with the script given below.
# run this cell
ames_data <- read_csv('data/ames.csv', col_types = cols()) |>
select(lot_area = Lot.Area,
year_built = Year.Built,
bsmt_sf = Total.Bsmt.SF,
first_sf = `X1st.Flr.SF`,
second_sf = `X2nd.Flr.SF`,
sale_price = SalePrice) |>
filter(!is.na(bsmt_sf))
ames_data
Question 2.1
{points: 3}
Split the data into a train dataset and a test dataset, based on a 70%-30% train-test split. Use set.seed(2019). Remember that we want to predict the sale_price based on all of the other variables.
Assign the objects to ames_split, ames_training, and ames_testing, respectively.
Use 2019 as your seed for the split.
set.seed(2019) # DO NOT CHANGE!
# your code here
#fail() # No Answer - remove if you provide an answer
ames_split <- initial_split (ames_data, prop = 0.7, strata = sale_price)
ames_testing <- testing(ames_split)
ames_training <- training (ames_split)
cell-416374a3ce562c44
Score: 3.0 / 3.0 (Top)
# We check that you've created objects with the right names below
# But all other tests were intentionally hidden so that you can practice deciding
# when you have the correct answer.
test_that('Did not create objects named ames_split, ames_training and ames_testing', {
expect_true(exists("ames_split"))
expect_true(exists("ames_training"))
expect_true(exists("ames_testing"))
})
### BEGIN HIDDEN TESTS
test_that('ames_split should be a rsplit object.', {
expect_true('rsplit' %in% class(ames_split))
})
test_that('ames_training is not a tibble.', {
expect_true('tbl' %in% class(ames_training))
})
test_that('ames_training does not contain the correct number of rows and/or columns.', {
expect_equal(dim(ames_training), c(2048, 6))
expect_equal(digest(int_round(sum(ames_training$lot_area), 2)), '0f473284653f451d0cb5cea966f4fc14')
expect_equal(digest(int_round(sum(ames_training$first_sf), 2)), '46b1007aee0c4135004ad8294c03f50d')
})
test_that('ames_testing is not a tibble.', {
expect_true('tbl' %in% class(ames_testing))
})
test_that('ames_testing does not contain the correct number of rows and/or columns.', {
expect_equal(dim(ames_testing), c(881, 6))
expect_equal(digest(int_round(sum(ames_testing$lot_area), 2)), 'ef74702fa3efc82f4d97a2cd2eda7ef1')
expect_equal(digest(int_round(sum(ames_testing$first_sf), 2)), '2b626f5c6c11e63c59ef70157245a8ec')
})
print("Success!")
### END HIDDEN TESTS
Question 2.2
{points: 3}
Let's start by exploring the training data. Use the ggpairs() function from the GGally package to explore the relationships between the different variables.
Assign your plot object to a variable named answer2.2.
set.seed(2020) # DO NOT REMOVE
options(repr.plot.height = 12, repr.plot.width = 12)
answer2.2 <- ames_training |>
ggpairs(
lower = list(continuous = wrap('points', alpha = 0.4)),
diag = list(continuous = "barDiag")
) +
theme(text = element_text(size = 20))
# your code here
#fail() # No Answer - remove if you provide an answer
answer2.2